<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends UserBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->model('repo/user_model', 'user_model');
    }

    public function index() {
        $this->load->helper('file');
        $user = $this->user_model->getUserById($this->user_id);
        $data = array('pageTitle' => 'Thông tin tài khoản', 'user' => $user);
        if($this->role == ROLE_SHOP_OWNER) {
            $this->load->model('repo/shop_model', 'shop_model');
            $shop = $this->shop_model->getShopByUserId($this->user_id);
            $data['shop_page_available'] = $this->shop_model->getAvailableShopMenuPage();
            $data['shop_page']           = $this->shop_model->getShopPages($shop->show_page);
            $data['shop_slide']          = $this->shop_model->getBannerSlide($shop->getSlug());
        }
        $this->renderView('backend/user/info', $data);
    }

    public function updateInfo() {
        $info = $this->input->post('info', true);
        $this->form_validation->set_rules('info[username]',   'lang:username',        'trim|required|max_length[150]|min_length[5]|xss_clean');
        $this->form_validation->set_rules('info[email]',      'lang:info_email',      'trim|required|valid_email|max_length[150]');
        $this->form_validation->set_rules('info[phone]',      'lang:info_phone',      'trim|required|numeric|max_length[15]|xss_clean');
        if(isset($info['home_phone']) && trim($info['home_phone'])!=''){
            $this->form_validation->set_rules('info[home_phone]', 'lang:info_home_phone', 'trim|numeric|max_length[15]|min_length[10]|xss_clean');
        }
        $this->form_validation->set_rules('info[address]',    'lang:info_address',    'trim|required|max_length[160]|min_length[10]|xss_clean');
        $this->form_validation->set_rules('info[skype]',      'lang:info_skype',      'trim|max_length[50]|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');

        if (isset($info['password'])) {
            if ($info['password'] != '') {
                $this->form_validation->set_rules('info[password]', 'lang:password', 'trim|required|max_length[100]|min_length[8]');
            } else {
                unset($info['password']);
            }
        }

        if ($this->form_validation->run() == false) {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aReturn);
            return;
        }

        $iExist = $this->user_model->checkUserExist($info, $this->user_id);
        if ($iExist == UPDATE_USER_DUPLICATE_USERNAME) {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('duplicate_username') . '</li></ul>');
            $this->renderJSON($aReturn);
            return;
        } elseif ($iExist == UPDATE_USER_DUPLICATE_EMAIL) {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('duplicate_email') . '</li></ul>');
            $this->renderJSON($aReturn);
            return;
        }

        if (isset($info['password']) && $info['password'] != '') {
            $info['password'] = $this->encrypt->encode($info['password']);
        }
        $result = $this->user_model->update($this->user_id, $info);
        if ($result) {
            $aReturn = array('code' => 1, 'title' => $this->lang->line('update_success'));
        } else {
            $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
        }

        $this->renderJSON($aReturn);
    }

    public function updateShopInfo() {
        $shop                = $this->input->post('shop', true);
        $shop_details        = $this->input->post('shop_details', true);
        $shop_payment_method = $this->input->post('shop_payment_method');
        $shop_id             = $this->encrypt->decode($this->input->post('shop_id'));
        $this->form_validation->set_rules('shop[title]', 'lang:shop_title', 'trim|required|max_length[100]|min_length[6]|xss_clean');
        $this->form_validation->set_rules('shop[slug]', 'lang:shop_slug', 'trim|required|max_length[100]|callback_slug_check|xss_clean');
        $this->form_validation->set_rules('shop[homepage]', 'lang:shop_homepage', 'trim|max_length[100]|xss_clean');
        $this->form_validation->set_rules('shop_details', 'lang:shop_details', 'trim|max_length['.CONTENT_LENGTH.']');
        $this->form_validation->set_rules('shop_payment_method', 'lang:shop_payment_method', 'trim|required|max_length['.CONTENT_LENGTH.']');
        $this->form_validation->set_error_delimiters('<li>', '</li>');

        //validate data
        $validation_errors = "";
        if ($this->form_validation->run() == false) {
            $validation_errors = validation_errors();
        }
        if ($shop_id == false) {
            $validation_errors .= "<li>" . $this->lang->line('shop_id_invalid') . "</li>";
        }
        if ($validation_errors != '') {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . $validation_errors . '</ul>');
            $this->renderJSON($aReturn);
            return;
        }

        //validate shop exist
        $this->load->model('repo/shop_model', 'shop_model');
        $iExist = $this->shop_model->checkShopExist($shop, $shop_id);
        if ($iExist > 0) {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('shop_duplicate') . '</li></ul>');
            $this->renderJSON($aReturn);
            return;
        }

        //update shop_info
        $shop['details'] = trim($shop_details);
        $shop['payment_method'] = trim($shop_payment_method);
        $result = $this->shop_model->update($shop_id, $shop);
        if ($result) {
            $aReturn = array('code' => 1, 'title' => $this->lang->line('update_success'));
        } else {
            $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
        }

        //set json output
        $this->renderJSON($aReturn);
    }

    public function updateSytemInfo(){
        $aReturn = array();
        $options = $this->input->post('options');
        $mailer = serialize($options['mailer']['value']);
        $options['mailer']['value'] = $mailer;
        $this->load->model('repo/options_model', 'options_model');
        $result = $this->options_model->update($options);
        if ($result) {
            $aReturn = array('code' => 1, 'title' => $this->lang->line('update_success'));
        } else {
            $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
        }
        //set json output
        $this->renderJSON($aReturn);
    }

    public function updateShopDetailInfo(){
        $aReturn         = array();
        $new_setting     = array();
        $shop_id         = $this->input->post('shop_id');
        $aShopPage       = $this->input->post('setting_page', true);
        $shop_template   = $this->input->post('setting_template');
        $shop_banner     = $this->input->post('setting_banner', true);
        $shop_slide      = $this->input->post('setting_slide', true);

        //check shop id
        if ($shop_id != false) {
            $shop_id = $this->encrypt->decode($shop_id);
            if ($shop_id == false) {
                $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
            }
        } else {
            $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
        }
        if(count($aReturn) > 0){
            $this->renderJSON($aReturn);
            die();
        }

        //get shop info
        $this->load->library('MyImage', 'myimage');
        $this->load->model('repo/shop_model', 'shop_model');
        $shop = $this->shop_model->getShopByUserId($this->user_id);

        //set shop page
        $shop_page = '';
        if(is_array($aShopPage) && count($aShopPage)>0){
            foreach ($aShopPage as $value) {
                if(is_numeric($value)){
                    $shop_page .= $value.',';
                }
            }
        }
        $shop_page = substr($shop_page, 0, -1);
        $new_setting['show_page'] = $shop_page;

        //set shop theme
        $theme_path = APPPATH.'views/shop-themes/'.$shop_template.'/'.$shop_template.'.php';
        if(!file_exists($theme_path)) {
            $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
            $this->renderJSON($aReturn);
            die();
        }
        $new_setting['template'] = $shop_template;

        //set shop banner
        if($shop_banner!='' && $shop_banner!=false){
            $imageInfo = explode('/', $shop_banner);
            if (count($imageInfo) != 2) {
                $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
                $this->renderJSON($aReturn);
                die();
            } else {
                if ($imageInfo[0] == 'temp') {
                    $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, SHOP_BANNER_IMAGE_URL, $imageInfo[1]);
                }
                $new_setting['banner'] = $imageInfo[1];
            }
        }

        //set shop slide, move to correct folder
        $aSlide = array();
        // if($shop_slide!=false){
        //     foreach($shop_slide as $img){
        //         $imageInfo = explode('/', $img);
        //         var_dump($imageInfo);
        //         if (count($imageInfo) != 2) {
        //             $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
        //         } else {
        //             if ($imageInfo[0] == 'temp') {
        //                 $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, SHOP_SLIDE_IMAGE_URL, $imageInfo[1]);
        //             }
        //             $aSlide[] = $imageInfo[1];
        //         }
        //     }
        // }

        // var_dump($aSlide);die();

        if(count($aReturn)==0){
            $new_setting['updated_at'] = get_current_date();
            $result = $this->shop_model->updateShopSetting($shop_id, $new_setting, $aSlide);
            if ($result) {
                $aReturn = array('code' => 1, 'title' => $this->lang->line('update_success'));
            } else {
                $aReturn = array('code' => 0, 'title' => $this->lang->line('update_fail'));
            }
        }
        $this->renderJSON($aReturn);
    }

    public function userRegisterForShop(){
        $aReturn = array(
            'pageTitle'=>'Mở gian hàng',
            'aJS' => assets('js/user.js', true)
            );
        $this->load->model('repo/shop_model', 'shop_model');
        $aReturn['registering'] = $this->shop_model->checkIfRegisteringShop($this->user_id);
        if($aReturn['registering']==false){
            $aReturn['info'] = new Shop_Entity();
        } else {
            $aReturn['info'] = $aReturn['registering'];
        }
        $this->renderView('backend/user/shop_info', $aReturn);
    }

    public function userSubmitRegisterForShop(){
        $aReturn = array();
        $shop                = $this->input->post('shop', true);
        $shop_payment_method = $this->input->post('shop_payment_method');
        $shop_details        = $this->input->post('shop_details');
        $shop_setting        = $this->input->post('shop_setting', true);
        $this->form_validation->set_rules('shop[title]',         'lang:shop_title',          'trim|required|max_length[100]|min_length[6]|xss_clean');
        $this->form_validation->set_rules('shop[slug]',          'lang:shop_slug',           'trim|required|max_length[100]|callback_slug_check|xss_clean');
        $this->form_validation->set_rules('shop[homepage]',      'lang:shop_homepage',       'trim|max_length[100]|callback_anchor_check|xss_clean');
        $this->form_validation->set_rules('shop_payment_method', 'lang:shop_payment_method', 'trim|required|max_length[6000]');
        $this->form_validation->set_rules('shop_details',        'lang:shop_details',        'trim|max_length[1000]');
        $this->form_validation->set_error_delimiters('<li>', '</li>');

        //validate data
        if ($this->form_validation->run() == false) {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aReturn);
            return;
        }

        //validate shop exist
        $this->load->model('repo/shop_model', 'shop_model');
        $iExist = $this->shop_model->checkShopExist($shop);
        if ($iExist > 0) {
            $aReturn = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('shop_duplicate') . '</li></ul>');
            $this->renderJSON($aReturn);
            return;
        }

        $date = get_current_date();
        $shop['user_id'] = $this->user_id;
        $shop['created_at'] = $date;
        $shop['details'] = $shop_details;
        $shop['payment_method'] = $shop_payment_method;

        $shop_setting['block_product_num'] = SHOP_DEFAULT_PRODUCT_BLOCK;
        $shop_setting['product_upload_per_month'] = SHOP_DEFAULT_PRODUCT_UPLOAD;
        $shop_setting['created_at'] = $date;

        $result = $this->shop_model->registerShop($shop, $shop_setting);
        if ($result) {
            $aReturn = array('code' => 1, 'text' => $this->lang->line('update_success'));
        } else {
            $aReturn = array('code' => 0, 'text' => $this->lang->line('update_fail'));
        }
        //set json output
        $this->renderJSON($aReturn);
    }
}
?>